package org.smart4j.framework.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public abstract class AspectProxy implements Proxy {

    private static final Logger LOGGER = LoggerFactory.getLogger(AspectProxy.class);

    @Override
    public Object doProxy(ProxyChian proxyChian) {
        Object result = null;
        Class<?> cls = proxyChian.getTargetClass();
        Method method = proxyChian.getTargetMehtod();
        Object[] params = proxyChian.getMethodParams();
        //1-
        begin();
        //2
        try {
            if (intercept(cls, method, params)) {
                before(cls, method, params);
                result = proxyChian.doProxyChain();
                after(cls, method, params, result);
            } else {
                result = proxyChian.doProxyChain();
            }
        } catch (Throwable e) {
            LOGGER.error("proxy failure", e);
            error(cls, method, params, e);
        } finally {
            end();
        }
        return result;
    }

    public void after(Class<?> cls, Method method, Object[] params, Object result) {
    }

    public void before(Class<?> cls, Method method, Object[] params) {
    }

    public void error(Class<?> cls, Method method, Object[] params, Throwable e) {
    }

    public boolean intercept(Class<?> cls, Method method, Object[] params) {
        return true;
    }

    public void begin() {

    }

    public void end() {

    }
}
